package com.zzyl.nursing.service.impl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.zzyl.common.ai.AIModelInvoker;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.vo.HealthReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 健康评估Service业务层处理
 *
 * @author alexis
 * @date 2025-01-06
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService {
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AIModelInvoker aiModelInvoker;
    /**
     * 查询健康评估
     *
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id) {
        return healthAssessmentMapper.selectById(id);
    }

    /**
     * 查询健康评估列表
     *
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    /*@Override
    public int insertHealthAssessment(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.insert(healthAssessment);
    }*/

    /**
     * 修改健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.updateById(healthAssessment);
    }

    /**
     * 批量删除健康评估
     *
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids) {
        return healthAssessmentMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除健康评估信息
     *
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id) {
        return healthAssessmentMapper.deleteById(id);
    }

    @Override
    public Long evaluation(HealthAssessment healthAssessment) {
        // 1.设计Prompt提示词（需要从Redis中读取当前身份证号对应的体检报告）
        String prompt = getPrompt(healthAssessment);

        // 2.调用百度千帆大模型，分析体检报告，获取分析结果
        String result = aiModelInvoker.qianfanInvoker(prompt);
        if (StringUtils.isEmpty(result)) {
            throw new BaseException("AI分析失败");
        }

        HealthReportVo healthReportVo = JSON.parseObject(result, HealthReportVo.class);

        // 3.将分析结果保存到数据库中
        // 4.返回保存的这条记录的id
        return insertHealthAssessment(healthReportVo, healthAssessment);
    }

    private Long insertHealthAssessment(HealthReportVo healthReportVo, HealthAssessment healthAssessment) {
        String idCard = healthAssessment.getIdCard();
        healthAssessment.setBirthDate(IDCardUtils.getBirthDateByIdCard(idCard));
        healthAssessment.setGender(IDCardUtils.getGenderFromIdCard(idCard));
        healthAssessment.setAge(IDCardUtils.getAgeByIdCard(idCard));

        double healthScore = healthReportVo.getHealthAssessment().getHealthIndex();
        healthAssessment.setHealthScore(String.valueOf(healthScore));
        healthAssessment.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel());

        //是否建议入住
        healthAssessment.setSuggestionForAdmission(getSuggestionForAdmission(healthScore));
        healthAssessment.setNursingLevelName(getNursingLevelName(healthScore));

        healthAssessment.setAdmissionStatus(1);
        healthAssessment.setTotalCheckDate(healthReportVo.getTotalCheckDate());
        healthAssessment.setAssessmentTime(LocalDateTime.now());
        healthAssessment.setReportSummary(healthReportVo.getSummarize());
        healthAssessment.setDiseaseRisk(JSONUtil.toJsonStr(healthReportVo.getRiskDistribution()));
        healthAssessment.setAbnormalAnalysis(JSONUtil.toJsonStr(healthReportVo.getAbnormalData()));
        healthAssessment.setSystemScore(JSONUtil.toJsonStr(healthReportVo.getSystemScore()));

        save(healthAssessment);
        return healthAssessment.getId();
    }

    private String getNursingLevelName(double healthScore) {
        // 处理边界
        if (healthScore < 0 || healthScore > 100) {
            throw new IllegalArgumentException("健康评分必须在0到100之间");
        }

        if(healthScore>=90){
            return "四级护理等级";
        }else if(healthScore>=80){
            return "三级护理等级";
        }else if(healthScore>=70){
            return "二级护理等级";
        }else if(healthScore>=60){
            return "一级护理等级";
        }else {
            return "特级护理等级";
        }
    }

    private Integer getSuggestionForAdmission(double healthScore) {
        if (healthScore >= 60) {
            return 0;
        }
        return 1;
    }

    private String getPrompt(HealthAssessment healthAssessment) {
        try (
                FileInputStream fileInputStream = new FileInputStream("D:\\Java\\zzyl\\houduan\\zzyl-cp423\\zzyl-nursing-platform\\src\\main\\resources\\prompts\\prompt.txt");
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                ){
            // 1.先从Redis中获取体检报告的内容
            String str = (String) redisTemplate.opsForHash().get(CacheConstants.HEALTH_REPORT_KEY, healthAssessment.getIdCard());

            redisTemplate.opsForHash().delete(CacheConstants.HEALTH_REPORT_KEY, healthAssessment.getIdCard());
            // 2.组装提示词
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                if (line.contains("体检内容如下：")) {
                    sb.append(str);
                }
            }
            return sb.toString();
        } catch (IOException e) {
            throw new BaseException("读取文件获取提示词失败");
        }
    }
}
